package com.akaovi.course;

import java.util.HashMap;
import java.util.Random;

/**
 * @author akaovi
 * @version 1.0
 * @description
 * @date 2022/10/31 10:38
 * @since 2022/10/31 10:38
 */
public class Main {

    public static void main(String[] args) {
        final Integer[] money = {0};

        Random random = new Random();
        Random moneyRandom = new Random();

        // lock
        Object lock = new Object();

        // 通信
        HashMap<String, Integer> map = new HashMap<>();
        map.put("cust", 0); // 0-可以消费  1-需要wait  2-需要唤醒  3-不动

        // 消费者线程
        Thread cust = new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(1000);

                    synchronized (lock) {
                        int moneyCus = moneyRandom.nextInt(100);
                        if (money[0] - moneyCus < 0) {
                            System.out.printf("我要消费: %d, 只有: %d元 不够, 等会儿...\n", moneyCus, money[0]);
                            lock.notify();
                            lock.wait();
                        } else {
                            money[0] -= moneyCus;
                            System.out.printf("消费者线程消费了: %d元, 剩余: %d元\n", moneyCus, money[0]);
                            if (money[0] < 20) {
                                lock.notify();
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        // 生产者线程
        Thread prod = new Thread(() -> {
            while (true) {
                try {
                    synchronized (lock) {
                        int moneyProd = moneyRandom.nextInt(100);
                        money[0] += moneyProd;
                        System.out.printf("生产者线程给予了: %d元, 当前有: %d元\n", moneyProd, money[0]);
                        lock.notify();
                        if (money[0] > 200) {
                            System.out.printf("还有%d, 给太多了, 我休息会儿\n", money[0]);
                            lock.wait();
                        }
                        Thread.sleep(2000);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        prod.start();
        cust.start();
//        try {
//            while (true) {
//                if (map.get("cust") == 2) {
//                    cust.notify();
//                    map.put("cust", 0);
//                } else if (map.get("cust") == 1) {
//                    cust.wait();
//                    map.put("cust", 3);
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }
}
